package com.shareppy.normanhttp;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

import com.shareppy.normanhttp.tasks.BgTaskParams;

public class HttpRequestParams implements BgTaskParams{
	
	public static final String USERNAME = "login_cred_name";
	public static final String PASSWORD = "login_cred_pwd";

	private Map<String, String> params;

	public HttpRequestParams() {
		this.params = new HashMap<String, String>();
	}

	public void addParam(String key, String value) {
		if (key != null && value != null) {
			params.put(key, value);
		}
	}

	public Set<String> keys() {
		return params.keySet();
	}

	@SuppressWarnings("unchecked")
	public <T> T get(String key) {
		return (T) params.get(key);
	}

	public void addSecurityParams(HttpRequestParams params, boolean useLoginSign) {

	}

	public void addParams(String[] qskeys, String[] qsvalues) {
		for (int i = 0; i < qskeys.length; i++) {
			addParam(qskeys[i], qsvalues[i]);
		}
	}

	public void remove(String key) {
		params.remove(key);
	}

	public boolean isEmpty() {
		return params.isEmpty();
	}

	public int size() {
		return params.size();
	}

	public void addParams(Map<String, String> extraParams) {
		if (extraParams != null) {
			params.putAll(extraParams);
		}
	}

	@Override
	public String toString() {
		if( isEmpty() ){
			return "";
		}
		StringBuilder str = new StringBuilder();
		Set<String> keys = new TreeSet<String>(keys());
		for (String key : keys) {
			try {
				str.append("&").append(key).append("=").append(URLEncoder.encode(params.get(key), "UTF-8"));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		return "?" + str.substring(1);
	}

	@Override
	public <V> void add(String key, V value) {
		addParam(key, (String) value);
	}
}